package com.lmt.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: Amazing
 * @Date: 2022/7/31 19:36
 * @Version: 1.0
 */
@Component
public class LoginCheckFilter extends ZuulFilter {

    // filter类型
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    // 此判断结果会决定run方法是否执行，如果返回true，则run方法执行，否者不执行run方法
    @Override
    public boolean shouldFilter() {
        // 放行公共静态资源和登录，注册路径
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取到请求路径
        String uri = request.getRequestURI();
        return !(uri.endsWith("/register") || uri.endsWith("/login") || uri.contains("static"));
    }

    // 这是核心方法
    @Override
    public Object run() throws ZuulException {
        // 从用户的请求头中获取token
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String token = request.getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //中文编码
        response.setContentType("application/json;charset=utf-8");
        // 判断token是否合规
        if (StringUtils.isBlank(token) && !tokenIsTrue(token)) {
            // 进入到此，说明token存在问题
            Map<Object, Object> hashMap = new HashMap<>();
            hashMap.put("success", false);
            hashMap.put("message", "未登录");
            hashMap.put("code", 402);
            hashMap.put("data", null);
            // 把hashmap转化为JSON字符串
            String hashMapStr = JSON.toJSONString(hashMap);
            response.setStatus(402);
            try {
                // 将数据响应给前台
                response.getWriter().write(hashMapStr);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 进行请求拦截，固定写法
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        // 这里返回结果没有任何意义，不用管
        return null;
    }

    private static boolean tokenIsTrue(String token) {
        // 此处需要编写判断token的业务代码
        return false;
    }
}
